﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Reflection;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

using THS.UMS.AO;
using THS.UMS.UI.Controls.Helpers;
using THS.UMS.UI.Utilities;

namespace THS.UMS.UI.Forms.Setup
{
    public partial class Setup : System.Web.UI.Page
    {

        #region "Page Events"

        protected void Page_Load(object sender, EventArgs e)
        {
            bool DBStatus = false;

            if (!IsPostBack)
            {
               DBStatus = VerifyDatabaseConn();
               if (DBStatus == true)
               {
                   pnlADCredentials.Visible = true;
               }
            }

        }

        protected void btnCheckAD_Click(object sender, EventArgs e)
        {
            bool isADVerified = false;

            pnlADerror.Visible = false;
            isADVerified = VerifyDirectory();
            if (isADVerified)
            {
                pnlADCredentials.Visible = false;
                pnlUser.Visible = true;
            }

        }

        protected void btnAdminAdd_Click(object sender, EventArgs e)
        {
            bool isAdminSet;

            isAdminSet = VerifyUserSec();
            if (isAdminSet)
            {
                pnlUser.Visible = false;
                // Load minor settings
                txtAppUrl.Text = "http://" + Request.Url.Host;
                txtAppTitle.Text = new AO.Setup().GetAppTitle();
                pnlOther.Visible = true;
            }
        }

        protected void btnOther_Click(object sender, EventArgs e)
        {
            FinalizeSettings();
        }



        #endregion

        #region "Page Functions"

        private bool VerifyDatabaseConn()
        {

            // Try to load the existing connection string
            var c = new Config();
            var db = new SqlConnectionStringBuilder(c.GetDatabaseSettings().ProviderConnectionString);
            if (!String.IsNullOrWhiteSpace(db.DataSource))
            {
                // Test existing connection
                if (new AO.Setup().VerifyConnectionString(c.GetDatabaseSettings().ProviderConnectionString))
                {
                    imageDB.ImageUrl = "~/Images/OKicon.png";
                    return true;
                }
                else
                {
                    imageDB.ImageUrl = "~/Images/NotOKicon.png";
                    pnlDBError.Visible = true;
                    return false;
                }

            }
            else
            {
                imageDB.ImageUrl = "~/Images/NotOKicon.png";
                pnlDBError.Visible = true;
                return false;
            }

        }


        private bool VerifyDirectory()
        {
            string server;
            if (!new AO.Setup().VerifyDirectoryAccess(txtAdDomain.Text, txtAdUsername.Text, txtAdPassword.Text, out server))
            {
                pnlADerror.Visible = true;
                imageAD.ImageUrl = "~/Images/NotOKicon.png";
                return false;
            }
            else
            {
                // Save Directory Settings
                AppSettings.SetValue("AdPath", "LDAP://" + txtAdDomain.Text);
                AppSettings.SetValue("AdUser", txtAdUsername.Text);
                AppSettings.SetValue("AdUserPass", txtAdPassword.Text);

                pnlADCredentials.Visible = true;
                pnlUser.Visible = true;
                imageAD.ImageUrl = "~/Images/OKicon.png";
                return true;
            }
        }

        private bool VerifyUserSec()
        {
            string verifiedUsername;
            bool IsUserSecVerified;

            if (new AO.Setup().DoesUserExist(out verifiedUsername))
            {
                    txtUpnUser.Text = verifiedUsername;
                    return false;
            }

            // Add User
            IsUserSecVerified = new AO.Setup().AddAdminUser(txtUpnUser.Text);
            if (IsUserSecVerified)
            {
                imageUser.ImageUrl = "~/Images/OKicon.png"; 
                return true;
            }
            else
            {
                imageUser.ImageUrl = "~/Images/NotOKicon.png";
                return false;
            }
        }

        private bool FinalizeSettings()
        {

            var retVal = true;

            // Save Application Settings
            if (!AppSettings.SetValue("AppTitle", txtAppTitle.Text)) retVal = false;
            if (!AppSettings.SetValue("AppUrl", txtAppUrl.Text)) retVal = false;

            if (!retVal)
            {
                omResult.Mode = OutputMessage.MessageMode.Failure;
                omResult.Message = "Failed! Could not save all needed changes.";
                omResult.Show();
                return false;
            }

            try
            {
                // Secure setup folder
                var sc = new Config("~/Forms/Setup/");
                var auth = sc.GetAuthorizationSettings();
                var rule = new AuthorizationRule(AuthorizationRuleAction.Deny);
                rule.Users.Add("*");
                auth.Rules.Add(rule);
                sc.SaveConfiguration();

                // Turn off installer and reload application
                var c = new Config();
                c.SetApplicationSetting("RunInstaller", "false");
                c.SaveConfiguration();

                // Redirect
                Response.Redirect("~/");
            }
            catch (Exception)
            {
                omResult.Mode = OutputMessage.MessageMode.Failure;
                omResult.Message = "Failed! Could not save configuration changes.";
                omResult.Show();
                return false;
            }


            return true;
        }

        #endregion



    }
}

